""" 待开发 """
from logger import log as logger
from flask import Blueprint
from flask_cors import CORS
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask_httpauth import HTTPTokenAuth
import os
import json
import request


def getTokenAuth():
    """
    开启token生成
    开启token验证
    支持查看token生成记录
    """
    token = Blueprint('token', __name__)
    CORS(token)

    httpTokenAuth = HTTPTokenAuth(scheme="token")
    __TokenRecords = {"records": []}
    __Users = []
    __Key = 'saftop key'
    __serializer = Serializer(__Key)
    __dir = './data'
    __tokenRecordFile = __dir + '/data.json'

    @httpTokenAuth.verify_token
    def verify_token(token):
        nonlocal __Users, __serializer  # 这里不能global __serializer,引用反而为None，报错，原因暂时未知
        try:
            data = __serializer.loads(token)
        except Exception as e:
            logger.error('token验证失败')
            logger.error(e)
            return False
        if 'user' in data:
            user = data['user']
            if user in __Users:
                return True
            # g.user = data['user']
        return False

    def loadRecords():
        """ 从文件读取以前保存得token数据 """
        nonlocal __TokenRecords, __Users
        try:
            if os.path.exists(__tokenRecordFile):
                rfile = open(__tokenRecordFile, "r")
                result = rfile.read()  # 这里必须用变量保存一下，直接json。loads会解析不了，原因未知
                __TokenRecords = json.loads(result)
                __Users = [item['user'] for item in __TokenRecords["records"]]
        except Exception as e:
            logger.error(e)
            logger.error("加载历史token失败,历史token不可用")

    loadRecords()

    @httpTokenAuth.error_handler
    def error_handler():
        return __ReturnErrorMsg(403, "token验证错误")

    def saveTokenRecord(user=None, timeLimit=None):
        """ 将生成Token的记录保存，但不记录Token本身[{'role':user,'timelimit':1}] """
        nonlocal __TokenRecords, __Users
        if user is not None and timeLimit is not None:
            tokenRecordItem = {}
            tokenRecordItem['user'] = user
            tokenRecordItem['timelimit'] = timeLimit
            tokenRecordItem['creationtime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            __TokenRecords["records"].append(tokenRecordItem)
            __Users.append(user)

        if not os.path.exists(__dir):
            os.makedirs(__dir)
        rfile = open(__tokenRecordFile, "w")
        rfile.write(str(__TokenRecords).replace("'", '"'))

    @token.route('/gentoken')
    def genToken():
        nonlocal __Users, __serializer, __Key  # 这里不用引用__key，引用会报错，原因未知
        try:
            # if username == 'saftop' and password == 'saftop':
            if 'user' in request.args.keys() and 'timelimit' in request.args.keys():
                user = request.args['user']  # Token描述，做什么用的，谁用的之类
                timeLimit = request.args['timelimit']  # Token 时间限制,单位H

                if user in __Users:
                    return 'please rename user'
                if timeLimit == 'F':
                    __serializer = Serializer(__Key)

                else:
                    try:
                        timeLimit = float(timeLimit)
                        timeLimit = int(timeLimit * 60 * 60)
                        __serializer = Serializer(__Key, expires_in=timeLimit)
                    except Exception as e:
                        logger.error(e)
                        return ''
                token = __serializer.dumps({'user': user})
                saveTokenRecord(user, timeLimit)
                return token
        except Exception as e:
            logger.error('生成Token失败，参数错误')
            logger.error(e)
            return '生成Token失败，参数错误'
        return ''

    @token.route('/user')
    def showUser():
        nonlocal __Users
        return str(__Users)

    @token.route('/userdetail')
    def showUserDetail():
        nonlocal __TokenRecords
        return __TokenRecords

    @token.route('/deluser/<user>')
    def delUser(user):
        nonlocal __Users, __TokenRecords
        try:
            if user in __Users:
                __Users.remove(user)
                for item in __TokenRecords["records"]:
                    if item['user'] == str(user):
                        __TokenRecords["records"].remove(item)
                        break
                saveTokenRecord()
                return 'success'
            return 'false'
        except Exception as e:
            logger.error(e)
            return 'false'

    app.register_blueprint(token, url_prefix="/token")
    return httpTokenAuth